package com.example.myapplication.api

import android.util.Log
import com.example.myapplication.model.Stock
import com.example.myapplication.model.StockPrice
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.text.SimpleDateFormat
import java.util.*

/**
 * 新浪财经API接口
 * 免费、无需注册、支持A股实时数据
 */
class SinaFinanceApi {
    
    companion object {
        private const val TAG = "📈StockAPI"  // 专用日志标签
        private const val BASE_URL = "https://hq.sinajs.cn/list="
        private const val HISTORY_URL = "https://quotes.money.163.com/service/chddata.html"
    }
    
    /**
     * 获取实时股票数据
     * @param symbols 股票代码列表，如：["sh600519", "sz000858"]
     */
    suspend fun getRealTimeData(symbols: List<String>): List<Stock> = withContext(Dispatchers.IO) {
        try {
            val symbolsStr = symbols.joinToString(",")
            val url = URL("$BASE_URL$symbolsStr")
            Log.i(TAG, "请求实时数据: $url")
            
            val connection = url.openConnection() as HttpURLConnection
            connection.requestMethod = "GET"
            // 添加请求头，模拟浏览器访问，避免403错误
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
            connection.setRequestProperty("Referer", "https://finance.sina.com.cn")
            connection.connectTimeout = 5000
            connection.readTimeout = 5000
            
            val responseCode = connection.responseCode
            Log.i(TAG, "响应码: $responseCode")
            
            if (responseCode == HttpURLConnection.HTTP_OK) {
                val reader = BufferedReader(InputStreamReader(connection.inputStream, "GBK"))
                val response = reader.readText()
                reader.close()
                
                Log.i(TAG, "响应内容长度: ${response.length}")
                val result = parseRealTimeData(response)
                Log.i(TAG, "✅ 成功解析 ${result.size} 只股票")
                result
            } else {
                Log.e(TAG, "❌ API请求失败，响应码: $responseCode")
                emptyList()
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ API请求异常: ${e.message}", e)
            emptyList()
        }
    }
    
    /**
     * 解析新浪财经实时数据
     * 数据格式：var hq_str_sh600519="贵州茅台,1650.00,1645.50,1680.50,..."
     */
    private fun parseRealTimeData(response: String): List<Stock> {
        val stocks = mutableListOf<Stock>()
        
        val lines = response.split("\n")
        for (line in lines) {
            if (line.isEmpty()) continue
            
            try {
                // 提取股票代码
                val symbolMatch = Regex("hq_str_(\\w+)=").find(line)
                val symbol = symbolMatch?.groupValues?.get(1) ?: continue
                
                // 提取数据部分
                val dataStart = line.indexOf("\"") + 1
                val dataEnd = line.lastIndexOf("\"")
                val data = line.substring(dataStart, dataEnd).split(",")
                
                if (data.size < 32) continue
                
                val name = data[0]
                val todayOpen = data[1].toDoubleOrNull() ?: 0.0
                val yesterdayClose = data[2].toDoubleOrNull() ?: 0.0
                val currentPrice = data[3].toDoubleOrNull() ?: 0.0
                val high = data[4].toDoubleOrNull() ?: 0.0
                val low = data[5].toDoubleOrNull() ?: 0.0
                val volume = data[8].toLongOrNull() ?: 0L
                
                val change = currentPrice - yesterdayClose
                val changePercent = if (yesterdayClose > 0) {
                    (change / yesterdayClose) * 100
                } else {
                    0.0
                }
                
                stocks.add(
                    Stock(
                        symbol = formatSymbol(symbol),
                        name = name,
                        currentPrice = currentPrice,
                        change = change,
                        changePercent = changePercent,
                        volume = volume
                    )
                )
            } catch (e: Exception) {
                e.printStackTrace()
                continue
            }
        }
        
        return stocks
    }
    
    /**
     * 获取历史K线数据
     * @param symbol 股票代码，如："sh600519"
     * @param days 获取天数
     */
    suspend fun getHistoryData(symbol: String, days: Int = 90): List<StockPrice> = withContext(Dispatchers.IO) {
        try {
            // 使用网易财经接口获取历史数据
            val code = symbol.substring(2) // 去掉sh/sz前缀
            val market = if (symbol.startsWith("sh")) "0" else "1"
            
            // 固定起始日期为2025年9月1日，获取真实日K线数据
            val startDate = "20250901"
            val endDate = SimpleDateFormat("yyyyMMdd", Locale.CHINA).format(Date())
            
            val urlString = "$HISTORY_URL?code=$market$code&start=$startDate&end=$endDate&fields=TCLOSE;HIGH;LOW;TOPEN;VOTURNOVER"
            val url = URL(urlString)
            Log.i(TAG, "📊 请求真实日K线: $symbol (从2025-09-01到今天)")
            
            val connection = url.openConnection() as HttpURLConnection
            connection.requestMethod = "GET"
            // 添加请求头，模拟浏览器访问
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
            connection.setRequestProperty("Referer", "https://quotes.money.163.com")
            connection.connectTimeout = 10000
            connection.readTimeout = 10000
            
            val responseCode = connection.responseCode
            Log.i(TAG, "📊 真实数据响应码: $responseCode")
            
            if (responseCode == HttpURLConnection.HTTP_OK) {
                val reader = BufferedReader(InputStreamReader(connection.inputStream, "GBK"))
                val response = reader.readText()
                reader.close()
                
                val result = parseHistoryData(response)
                if (result.isNotEmpty()) {
                    val firstDate = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(Date(result.first().timestamp))
                    val lastDate = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(Date(result.last().timestamp))
                    Log.i(TAG, "✅ 成功获取真实日K线 ${result.size} 条：$firstDate 至 $lastDate")
                } else {
                    Log.w(TAG, "⚠️ 未获取到数据，可能需要检查股票代码或网络")
                }
                result
            } else {
                Log.e(TAG, "❌ API请求失败，响应码: $responseCode")
                emptyList()
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 获取真实数据异常: ${e.message}", e)
            emptyList()
        }
    }
    
    /**
     * 解析历史数据
     * CSV格式：日期,股票代码,名称,收盘价,最高价,最低价,开盘价,成交量
     */
    private fun parseHistoryData(csv: String): List<StockPrice> {
        val prices = mutableListOf<StockPrice>()
        val lines = csv.split("\n")
        
        // 跳过标题行
        for (i in 1 until lines.size) {
            val line = lines[i].trim()
            if (line.isEmpty()) continue
            
            try {
                val data = line.split(",")
                if (data.size < 8) continue
                
                val dateStr = data[0]
                val close = data[3].toDoubleOrNull() ?: continue
                val high = data[4].toDoubleOrNull() ?: continue
                val low = data[5].toDoubleOrNull() ?: continue
                val open = data[6].toDoubleOrNull() ?: continue
                val volume = data[7].toLongOrNull() ?: 0L
                
                val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA)
                val timestamp = dateFormat.parse(dateStr)?.time ?: continue
                
                prices.add(
                    StockPrice(
                        timestamp = timestamp,
                        open = open,
                        high = high,
                        low = low,
                        close = close,
                        volume = volume
                    )
                )
            } catch (e: Exception) {
                e.printStackTrace()
                continue
            }
        }
        
        return prices.reversed() // 按时间正序排列
    }
    
    /**
     * 格式化股票代码
     * sh600519 -> 600519
     */
    private fun formatSymbol(symbol: String): String {
        return symbol.replace("sh", "").replace("sz", "")
    }
    
    /**
     * 标准化股票代码
     * 600519 -> sh600519
     * 000858 -> sz000858
     */
    fun normalizeSymbol(symbol: String): String {
        return when {
            symbol.startsWith("6") -> "sh$symbol"
            symbol.startsWith("0") || symbol.startsWith("3") -> "sz$symbol"
            else -> symbol
        }
    }
}

